package edu.taru.office.shiro.realm;

import edu.taru.office.common.Constants;
import edu.taru.office.common.SessionUser;
import edu.taru.office.pojo.User;
import edu.taru.office.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 权限核心类
 */
public class OfficeShiroRealm  extends AuthorizingRealm {

       private Logger logger  = LoggerFactory.getLogger(OfficeShiroRealm.class);

    @Autowired
    UserService userService;


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 身份认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username =utoken.getUsername();
        char [] temp =utoken.getPassword();
        String password="";
        if(temp!=null){
            password=new  String(temp);
        }

        //统一由声明方式异常处理
        User user =userService.login(username,password);
        if(user==null) {
            logger.info("没有找到登录用户");
            throw new UnknownAccountException("用户名或者密码错误");
        }else{
            if(user.getLocked().intValue()==0){
                throw  new  LockedAccountException("账户被锁定");
            }

        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUsername(), // 用户名
                user.getPassword(), // 密码
                getName()
        );
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute(Constants.LOGIN_USER_KEY,new SessionUser(user.getId(),user.getUsername(),user));
        return authenticationInfo;
    }
}
